<template>
  <div class="hello">
    <!-- form按回车键会自动提交 -->
    <!-- @submit.prevent关闭自动提交 -->
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" @submit.prevent="">
      <el-form-item prop="inputTitle" label-width="0px">
        <!--  @keyup.enter 点击回车键触发 -->
        <el-input
          placeholder="请输入内容，按回车键添加"
          v-model.trim="ruleForm.inputTitle"
          @keyup.enter="addTodo('ruleForm')"
          clearable
        />
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue';
// 导入TodoItemModel模块
import { TodoItemModel } from '@/type-scripts/todo-model';

export default defineComponent({
  name: 'Header',
  props: {
    // 接收父组件传入的函数对象
    // 添加自定义验证
    addTodoItem: {
      type: Function,
      required: true,
    },
  },
  // setup不能使用this对象
  // 将props以参数形式传入
  //   setup(props) {
  //     let inputTitle = ref('');

  //     // 按回车键添加一个新的todo项
  //     let addTodo = () => {
  //       const newItem = new TodoItemModel(Date.now(), inputTitle.value);
  //       props.addTodoItem(newItem);
  //     };

  //     return {
  //       inputTitle,
  //       addTodo,
  //     };
  //   },

  data() {
    var checkInputTitle = (rule: Object, value: string, callback: Function) => {
      if (!value) {
        return callback(new Error('添加项不能为空'));
      }
      if (value.length < 3) {
        return callback(new Error('长度需要大于3个字符'));
      }
      if (value.length > 10) {
        return callback(new Error('长度需要小于10个字符'));
      }
      return callback();
    };

    return {
      ruleForm: {
        inputTitle: '',
      },
      rules: {
        // 使用内置表单验证
        // inputTitle: [
        //   { required: true, message: '请输入todo名称', trigger: 'blur' },
        //   { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' },
        // ],

        inputTitle: [{ validator: checkInputTitle, trigger: 'blur' }],
      },
    };
  },

  methods: {
    // 按回车键添加一个新的todo项
    addTodo: function(formName: string) {
      const elForm: any = this.$refs[formName];
      console.log(elForm);

      elForm.validate((valid: Boolean) => {
        if (valid) {
          const newItem = new TodoItemModel(Date.now(), this.ruleForm.inputTitle, false);
          this.$props.addTodoItem(newItem);
        } else {
          return false;
        }
      });
    },
  },
});
</script>

<style lang="scss" scoped></style>
